package com.chen.spring.cloud.miniapp.api.feign.controller;

import cn.hutool.http.HttpUtil;
import com.chen.entity.User;
import com.chen.spring.cloud.miniapp.api.feign.service.WechatService;
import com.chen.util.MapperUtils;
import com.chen.util.R;
import com.chen.vo.WxCode2Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/Wechat")
public class WechatController {

    @Value("appid")
    private String appid;

    @Value("appsecret")
    private String appsecret;

    @Value("grant_type")
    private String grant_type;

    @Autowired
    private WechatService wechatService;


    @RequestMapping("/getOpenid")
    public R getOpenid(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid='+" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=" + grant_type;
        String result = HttpUtil.get(url);
        try {
            WxCode2Session wxCode2Session = MapperUtils.json2pojo(result, WxCode2Session.class);
            if (wxCode2Session.getErrcode() != null){
                return R.error(wxCode2Session.getErrcode(),wxCode2Session.getErrmsg());
            }
            String userjson = wechatService.addUser(wxCode2Session);
            User user = MapperUtils.json2pojo(userjson, User.class);
            return R.ok();
        } catch (Exception e){
            e.printStackTrace();
        }
        return R.error();
    }
}
